package org.wzq.mdm;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import org.json.JSONException;
import org.json.JSONObject;
import org.wzq.base.AppInfo;
import org.wzq.config.AppConfig;
import org.wzq.config.AppUrl;
import org.wzq.utils.HttpConnection;
import org.wzq.utils.Logger;

/**
 * project: android
 * date: 14-11-5
 * author: wzq
 * description: TODO
 */
public class SocketService extends Service {
    private Logger logger = Logger.newLogger(true, SocketService.class);

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // 工作流程:
    // -> app check
    // -> device register
    // -> socket setup
    // -> send/receive msg

    /**
     * @return true if check passed
     */
    public boolean appCheck() {
        String url = AppUrl.getHostIp() + "/appCheck";
        String body = null;
        JSONObject sb = new JSONObject();
        try {
            sb.put("appKey", AppConfig.APPKEY);
            sb.put("appInfo", AppInfo.getInfoJson());
            body = sb.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String result = HttpConnection.post(url, body);
        logger.v(result == null ? "null" : result);

        //
        if (result == null) {
            return false;
        }
        try {
            JSONObject json = new JSONObject(result);
            if ("ok".equals(json.get("status"))) {
                return true;
            }
        } catch (JSONException e) {
            logger.e("app check, invalid format");
        }
        return false;
    }

    public void deviceReg() {
    }

    public void socketSetup() {
    }

}
